﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using XiaoShuTong.Client.Dto;
using XiaoShuTong.Client.Util;

namespace XiaoShuTong
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        public Login()
        {
            InitializeComponent();

            var n = AppConfig.GetSettingString("name");
            if (!string.IsNullOrWhiteSpace(n))
            {
                name.Text = n;
            }

            var p = AppConfig.GetSettingString("pwd");
            if (!string.IsNullOrWhiteSpace(p))
            {
                pwd.Password = p;
            }
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                MemberLoginDto memberLoginDto = new MemberLoginDto { Name = name.Text, Pwd = pwd.Password, ClinetId = ComputerUniqueHelper.GetCPUID() };

                string jsonData = JsonConvert.SerializeObject(memberLoginDto);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync("http://xst.aj011.com/api/Member/Login", content);
                // 处理响应
                string responseContent = await response.Content.ReadAsStringAsync();
                var rsp = JsonConvert.DeserializeObject<BaseResponse>(responseContent);

                if (rsp.code == 200)
                {
                    AppConfig.UpdateSettingString("name", name.Text);
                    AppConfig.UpdateSettingString("pwd", pwd.Password);

                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();

                    this.Close();
                }
                else
                {
                    MessageBox.Show(rsp.msg);
                }

            }

        }

        public class MemberLoginDto
        {
            public string Name { get; set; }
            public string Pwd { get; set; }
            public string ClinetId { get; set; }
        }

    }
}
